/*
 * $HeadURL: $
 * $Id: $
 * Copyright (c) 2011 by Ericsson, all rights reserved.
 */
package org.jample.spring.ws.client;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;

import net.sf.json.JSONArray;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.methods.ByteArrayRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;

import com.google.common.collect.Lists;

/**
 * @author eccicce
 * @version $Revision: $
 * 
 */
public class RestfulClient {

    /** Revision of the class */
    public static final String _REV_ID_ = "$Revision: $";

    protected HttpClient client;

    @PostConstruct
    protected void init() {
        MultiThreadedHttpConnectionManager manager = new MultiThreadedHttpConnectionManager();
        HttpConnectionManagerParams para = new HttpConnectionManagerParams();
        para.setConnectionTimeout(30000);
        para.setSoTimeout(30000);
        para.setDefaultMaxConnectionsPerHost(20);
        para.setMaxTotalConnections(20);
        para.setStaleCheckingEnabled(true);
        manager.setParams(para);
        client = new HttpClient(manager);
    }

    public void post(List<Map> params) {
        // build up the message
        PostMethod post = new PostMethod("http://127.0.0.1:18080/rest/1.0/aaa/bbb");


        JSONArray jsonArray = JSONArray.fromObject(params);

        // set request body
        RequestEntity entity = new ByteArrayRequestEntity(jsonArray.toString().getBytes());
        post.setRequestEntity(entity);

        // send it out
        try {
            int status = client.executeMethod(post);
            if (status == HttpStatus.SC_OK) {
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            post.abort();
            post.releaseConnection();
        }
    }

    private static Map buildTicketInfo() {
        Map<String, Object> info = new HashMap<String, Object>();
        info.put("msisdn", "134545322");
        info.put("prt", "1341ddaq");
        info.put("ServiceId", "fdafa");
        return info;
    }

    public static void main(String[] args) {

        RestfulClient client = new RestfulClient();
        client.init();
        List list = Lists.newArrayList(buildTicketInfo(), buildTicketInfo());
        client.post(list);
    }
}
